package com.mtr.databoard.application.screens;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mtr.databoard.domain.middlewares.Parameter;
import com.mtr.databoard.domain.screens.IMiddlewareMessageSender;
import com.mtr.databoard.domain.screens.MiddlewareExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Component
public class HttpAuthHandler extends TextWebSocketHandler {
    private final MiddlewareExecutor middlewareExecutor;

    public HttpAuthHandler(MiddlewareExecutor middlewareExecutor) {
        this.middlewareExecutor = middlewareExecutor;
    }

    /**
     * socket 建立成功事件
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session)  {
        Object token = session.getAttributes().get("token");
        if (token != null) {
            // 用户连接成功，放入在线用户缓存
            var screenId = UUID.fromString(token.toString().split("=")[1]);
            middlewareExecutor.runBackgroundExecuteTask(session.getId(), screenId, new IMiddlewareMessageSender() {
                @Override
                public boolean send(String screenId, String componentCode, Object data) throws IOException {
                    var result = new JSONObject();
                    result.put("screenId", screenId);
                    result.put("componentCode", componentCode);
                    if (data != null)
                        result.put("data", data);
                    try
                    {
                        session.sendMessage(new TextMessage(result.toJSONString()));
                        return true;
                    }
                    catch (Exception ex){
                        System.out.println(ex);
                        return false;
                    }
                }
            });

        } else {
            System.out.println("用户登录已经失效!");
        }
    }

    /**
     * 接收消息事件
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 获得客户端传来的消息
        String payload = message.getPayload();

        JSONObject jsonObject = JSONObject.parseObject(payload);

        UUID screenId = UUID.fromString(jsonObject.getString("screenId"));
        String componentCode = jsonObject.getString("componentCode");


        List<Parameter> parameterList = new ArrayList<>();

        try {
            var jsonArr = jsonObject.getJSONArray("parameters");
            for (var jsonobj : jsonArr) {
                var parameter = ((JSONObject) jsonobj).toJavaObject(Parameter.class);
                parameterList.add(parameter);
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }


        var value = middlewareExecutor.execute(session.getId(), screenId, componentCode, parameterList);
        //var valueStr = JSON.toJSONString(value);

        var result = new JSONObject();
        result.put("screenId", screenId);
        result.put("componentCode", componentCode);
        if (value != null)
            result.put("data", value.getData());
        //value.setData(null);
        session.sendMessage(new TextMessage(result.toJSONString()));
    }

    /**
     * socket 断开连接时
     *
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Object token = session.getAttributes().get("token");
        if (token != null) {
            // 用户退出，移除缓存

        }
    }

}